package com.kerrykidz.system.util.tag;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kerrykidz.system.util.UserUtil;

/**
 * 
 * @Desc 重复验证过滤器
 * @author QUINN
 * @date 2014年9月10日上午9:50:18
 */
public class TokenFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	private static List<String> URLS = new ArrayList<String>();

	static {
		URLS.add("/login.shtml");
		URLS.add("/common/repeatSubmit.shtml");
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException,
			ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;

		String url = request.getServletPath();
		String contextPath = request.getContextPath();

		if (URLS.contains(url)) {
			arg2.doFilter(arg0, arg1);
			return;
		}

		/*
		 * 检查会话
		 */
		if (this.noLogin()) {
			response.sendRedirect(contextPath + "/login.shtml");
			return;
		}

		/*
		 * 检查TOKEN
		 */

		if (!validateToken(request)) {
			response.sendRedirect(contextPath + "/common/repeatSubmit.shtml");
			return;
		}

		arg2.doFilter(arg0, arg1);
	}

	/**
	 * 
	 * @Desc 检查参数是否有TOKEN,如果有返回验证结果,如果没有返回true
	 * @author QUINN
	 * @date 2014年9月10日上午11:03:06
	 * @param request
	 * @return
	 */
	private boolean validateToken(HttpServletRequest request) {
		String token = request.getParameter(TokenUtils.TOKEN_SESSION_KEY);
		return "GET".equals(request.getMethod()) || StringUtils.isBlank(token)
				|| TokenUtils.validateToken(token, request.getSession());
	}

	/**
	 * 
	 * @Desc 验证会话是否存在
	 * @author QUINN
	 * @date 2014年9月10日上午11:37:36
	 * @param session
	 * @return
	 */
	private boolean noLogin() {
		return UserUtil.getUserFromSession() == null;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		System.out.println(RequestMethod.GET.toString().equals("GET"));
	}

}
